package com.hnevc.listviewdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button mBtnBaseAdapter;
    //TODO 1：定义ListView字段变量,定义食品名称数组。
    ListView mListView;
    String[] foodNames;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        initEvent();
    }



    private void initView() {
        mBtnBaseAdapter = (Button) findViewById(R.id.id_btn_base_adapter);
        //TODO 2：获取布局文件中的控件
        mListView = (ListView) findViewById(R.id.id_lv_base);


    }

    private void initData() {
        //TODO 3：获取食品名称数据
        foodNames = getResources().getStringArray(R.array.foodName);
    }
    private void initEvent() {
        mBtnBaseAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 5: 创建MyBaseAdatper对象，并将其设置为ListView控件适配器
                MyBaseAdapter adapter = new MyBaseAdapter();
                mListView.setAdapter(adapter);
            }
        });
    }
    //TODO 4：定义BaseAdapter类的扩展类MyBaseAdapter
    class MyBaseAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return foodNames.length;
        }

        @Override
        public Object getItem(int position) {
            return foodNames[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item,null);
            TextView tvFoodName = (TextView) view.findViewById(R.id.id_tv_foodName);
            tvFoodName.setText(foodNames[position]);
            return view;
        }
    }

}
